//
//  NetWorkUtil.h
//  Andy
//
//  Created by mac on 15/7/16.
//  Copyright (c) 2015年 Andy. All rights reserved.
//

#import "NetWorkUtil.h"
#import <AFNetworking.h>
#import "Digest.h"
#import <SSKeychain/SSKeychain.h>
#import "AppUtils.h"
#import "SVProgressHUD.h"

@interface NetWorkUtil()


@end

@implementation NetWorkUtil

- (instancetype)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}

#pragma mark - Public Method

+(NSString *)getImagesBaseUrl {
    //https://192.168.1.100:1443/EChineseMedicine/rs/FileRS/resourceImage/
    //http://ecm-user.oss-cn-beijing.aliyuncs.com/image/
    return @"http://ecm-user.oss-cn-beijing.aliyuncs.com/image/";
}

+(NSString *)getVoicesBaseUrl {
    return @"http://ecm-user.oss-cn-beijing.aliyuncs.com/voice/";
}

+ (NSString *)replaceCharacter:(NSString *)oStr withString:(NSString *)nStr inString:(NSString *)string
{
    if (oStr && nStr) {
        NSMutableString *_str = [NSMutableString stringWithString:string];
        [_str replaceOccurrencesOfString:oStr withString:nStr options:NSCaseInsensitiveSearch range:NSMakeRange(0, _str.length)];
        return _str;
    }
    else
        return oStr;
}

/**
 *  请求Opinion Server Api 接口方法
 *
 *  @param request 自定义的Request请求
 *  @param success 请求成功,返回Response对象
 *  @param failure 请求失败
 *  @param cached  是否进行缓存
 */
+ (void)requestWithPOST:(NetWorkBaseRequest *)request success:(void (^)(NetWorkBaseResponse *responseObject))success failure:(void (^)(NSError *error))failure cache:(BOOL)cached{
    NSUserDefaults *doctorUser=[NSUserDefaults standardUserDefaults];
    
    if([[doctorUser objectForKey:@"refreshtoken"] isEqualToString:@"refreshtoken"])
    {
        [doctorUser setObject:@"yishuxin" forKey:@"refreshtoken"];
    }
    else
    [SVProgressHUD show];
    [self callBackrequestPost:request success:success failure:failure cache:cached callBackCounts:3];
    
}



+(void)playerVoiceWithVoiceName:(NSString *)voiceName success:(void (^)(NSString *))success failure:(void (^)(NSError *))failure {
    [SVProgressHUD show];
    
    if (!voiceName) {
        if (failure) {
            failure([NSError errorWithDomain:@"name为空" code:-1 userInfo:nil]);
        }
        [SVProgressHUD dismiss];
        return;
    }
    
    //    阿里云音频请求地址：
    //http://ecm-user.oss-cn-beijing.aliyuncs.com/voice/
    //    100服务器音频请求地址：
    //https://192.168.1.100:1433/EChineseMedicine/rs/FileRS/resourceVoice/
    
    //下载附件
    NSString *path = [NSString stringWithFormat:@"https://192.168.1.100:1433/EChineseMedicine/rs/FileRS/resourceVoice/%@", voiceName];
    
    NSString *myPath = [NSString stringWithFormat:@"%@/Documents/DataCache/%@",NSHomeDirectory(), path];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    
    //创建当前的路径
    BOOL isSuc = [fileManager createDirectoryAtPath:myPath withIntermediateDirectories:YES attributes:nil error:nil];
    if (!isSuc) {
        NSLog(@"创建路径失败");
        if (failure) {
            failure([NSError errorWithDomain:@"创建路径失败" code:-1 userInfo:nil]);
        }
        [SVProgressHUD dismiss];
        return;
    }
    
    
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:path]]];
    operation.inputStream   = [NSInputStream inputStreamWithURL:[NSURL URLWithString:path]];
    operation.outputStream  = [NSOutputStream outputStreamToFileAtPath:myPath append:NO];
    
#warning 正式发布时 取消 下行代码
    [operation.securityPolicy setAllowInvalidCertificates:YES];
    
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        [SVProgressHUD dismiss];
        success(@"1");
        return;
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        //下载失败
        [SVProgressHUD dismiss];
        failure(error);
    }];
    
    
    
}


+ (void)callBackrequestPost:(NetWorkBaseRequest *)request success:(void (^)(NetWorkBaseResponse *responseObject))success failure:(void (^)(NSError *error))failure cache:(BOOL)cached  callBackCounts:(int)callBackCounts ;
{
    
    if (!request) {
        NSLog(@"[ERROR] request cannot be NULL");
        if (failure) {
            failure([NSError errorWithDomain:@"" code:-1 userInfo:nil]);
        }
        [SVProgressHUD dismiss];
        return;
    }
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    manager.requestSerializer.timeoutInterval = 10;
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager.requestSerializer setCachePolicy:NSURLRequestReturnCacheDataElseLoad];
    [manager.requestSerializer setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    
#warning 正式发布时 取消 下行代码
    [manager.securityPolicy setAllowInvalidCertificates:YES];
    
    
    NSString *tokenValue = [SSKeychain passwordForService:[AppUtils appServiceName] account:[AppUtils tokenKey]];
    NSLog(@"%@",tokenValue);
   if (!tokenValue) {
        tokenValue = @"";
    }
    
    [request.paramDic setValue:tokenValue forKey:@"token"];
    
    //   NSString *encryptParam = request.getEncrptPostDataString;
    
    [manager POST:request.stringOfApiURLString parameters:request.paramDic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"___________%@",request.stringOfApiURLString);
        NSDictionary *dic = responseObject;//operation.request.cachePolicy
        [SVProgressHUD dismiss];
        
        if (dic) {
            
            @try{
                //解决若是json格式出错崩溃问题，判断status=0为成功
                NSString *responseClassName =  [NetWorkUtil replaceCharacter:@"Request" withString:@"Response" inString:NSStringFromClass([request class])];
                NetWorkBaseResponse *response = [[NSClassFromString(responseClassName) alloc] initWithDictionary:dic];
                if (response && success) {
                    //缓存
                    if (cached) {
                        NSCachedURLResponse *resp = [[NSCachedURLResponse alloc] initWithResponse:operation.response data:operation.responseData];
                        [[NSURLCache sharedURLCache] storeCachedResponse:resp forRequest:operation.request];
                    }
                    success(response);
                }else{
                    failure([NSError errorWithDomain:@"接口出错" code:-1 userInfo:nil]);
                    [SVProgressHUD dismiss];
                }
            }@catch(NSException *exception) {
                failure([NSError errorWithDomain:@"接口返回数据格式出错" code:-1 userInfo:nil]);
                [SVProgressHUD dismiss];
            }
        }else if (failure) {
            [SVProgressHUD dismiss];
            failure([NSError errorWithDomain:@"接口出错" code:-1 userInfo:nil]);
        }else{
            NSLog(@"[ERROR] failure not exist!");
            [SVProgressHUD dismiss];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
      
        if (failure) {
            if (error.code == 3) {
                
                if (callBackCounts > 0) {
                    int a = callBackCounts - 1;
                    //
                    //                    //GCD
                    //                    __weak __typeof(self)weakSelf = self;
                    //                    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(200 * NSEC_PER_USEC));//NSEC_PER_USEC 毫秒
                    //                    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                    [self callBackrequestPost:request success:success failure:failure cache:cached callBackCounts:a];
                    //                    });
                }
            }
            [SVProgressHUD dismiss];
            failure(error);
        }else{
            [SVProgressHUD dismiss];
            NSLog(@"[ERROR] failure not exist!");
        }
    }];
}
/*______上传 所问问题   只有文字的________**littleSun_zheng**/

/**
 *  请求Opinion Server Api 接口方法
 *
 *  @param request 自定义的Request请求
 *  @param userInfoId 对应人的唯一标示（用户本人  和  关系人）
 *  @param token token值
 *  @param imageDataArray  盛放图片（文字）的数组
 *  @param success 请求成功,返回Response对象
 *  @param failure 请求失败
 *  @param cached  是否进行缓存
 */

+ (void)requestWithPOST:(NetWorkBaseRequest *)request  WithToken:(NSString *)token WithImageDataArray:(NSMutableArray *)imageDataArray
                success:(void (^)(NetWorkBaseResponse *responseObject))success
                failure:(void (^)(NSError *error))failure
                  cache:(BOOL)cached
{
    
    
    if (!request) {
        NSLog(@"[ERROR] request cannot be NULL");
        if (failure) {
            failure([NSError errorWithDomain:@"" code:-1 userInfo:nil]);
        }
        return;
    }
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    
    [manager.requestSerializer setValue:@"multipart/form-data;charset=utf-8"forHTTPHeaderField:@"Content-Type"];
    
    manager.requestSerializer.timeoutInterval = 10;
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager.requestSerializer setCachePolicy:NSURLRequestReturnCacheDataElseLoad];
    
    NSString *tokenValue = [SSKeychain passwordForService:[AppUtils appServiceName] account:[AppUtils tokenKey]];
    if (!tokenValue) {
        tokenValue = @"";
    }
    //    NSString *baseURL = @"http://www.ezhongyi591.com:8080/EChineseMedicine/rs";
    //    NSString *moduleName = @"UserRS";
    //    NSString *postHeardUrl = [NSString stringWithFormat:@"%@/%@/uploadUserIcon",baseURL,moduleName];
    //
    
    //http://www.ezhongyi591.com:8080/EChineseMedicine/rs/UserRS/uploadUserIcon
    
    //对传进来的 图片  数组进行遍历 然后保存到字典中
    for (NSData *imgData in imageDataArray)
    {
        
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        
        
        //用这个当图片的名字，一起到图片名不重复的效果
        [dateFormatter setDateFormat:@"yyyyMMddHHmmssSSSS"];
        
        NSString *pictname;
        NSString *picFileName;
        
        pictname = [NSString stringWithFormat:@"/%@.jpg",[dateFormatter stringFromDate:[NSDate date]]];
        picFileName = [NSString stringWithFormat:@"/%@file",[dateFormatter stringFromDate:[NSDate date]]];
        
        //        NSString *encryptParam = request.getEncrptPostDataString;
        
        [request.paramDic setValue:imgData forKey:@"file"];
        [request.paramDic setValue:tokenValue forKey:@"token"];
        
        
        //        NSMutableDictionary *parametersDic = [NSMutableDictionary dictionaryWithObjectsAndKeys:encryptParam,@"encryptParam",imgData,@"file",tokenValue,@"token",nil];
        
        
        
        [manager POST:request.stringOfApiURLString parameters:request.paramDic constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
         {
             
             [formData appendPartWithFileData:[request.paramDic objectForKey:@"file"] name:picFileName fileName:[NSString stringWithFormat:@"%@",pictname] mimeType:@"image/jpg"];
             
             
         }
              success:^(AFHTTPRequestOperation *operation, id responseObject)
         
         {
             
             {
                 
                 NSDictionary *dic = responseObject;//operation.request.cachePolicy
                 
                 if (dic)
                 {
                     @try{
                         
                         //                         NSError *error = nil;
                         //                         NSString *encryptKey = [dic objectForKey:@"encryptKey"];
                         //                         NSString *data = [dic objectForKey:@"data"];
                         //                         if (!encryptKey || !data) {
                         //                             failure([NSError errorWithDomain:@"接口返回数据格式出错" code:-1 userInfo:nil]);
                         //                             return ;
                         //                         }
                         //
                         //                         NSString* aesKey = [[Digest sharedInstance] rsaDecryptString:encryptKey];
                         //                         CocoaSecurityResult *text =  [CocoaSecurity aesDecryptWithBase64ESPC:data key:aesKey];
                         //
                         //                         if (!text.utf8String) {
                         //                             failure([NSError errorWithDomain:@"接口返回数据格式出错" code:-1 userInfo:nil]);
                         //                             return ;
                         //                         }
                         //
                         //                         NSDictionary *apiDic = [NSJSONSerialization JSONObjectWithData:text.data options:0 error:&error];
                         //                         if (!apiDic || error) {
                         //                             failure([NSError errorWithDomain:@"接口返回数据格式出错" code:-1 userInfo:nil]);
                         //                             return ;
                         //                         }
                         
                         //解决若是json格式出错崩溃问题，判断status=0为成功
                         NSString *responseClassName =  [NetWorkUtil replaceCharacter:@"Request" withString:@"Response" inString:NSStringFromClass([request class])];
                         NetWorkBaseResponse *response = [[NSClassFromString(responseClassName) alloc] initWithDictionary:dic];
                         if (response && success) {
                             //缓存
                             if (cached) {
                                 NSCachedURLResponse *resp = [[NSCachedURLResponse alloc] initWithResponse:operation.response data:operation.responseData];
                                 [[NSURLCache sharedURLCache] storeCachedResponse:resp forRequest:operation.request];
                             }
                             success(response);
                         }else{
                             failure([NSError errorWithDomain:@"接口出错" code:-1 userInfo:nil]);
                         }
                     }@catch(NSException *exception) {
                         failure([NSError errorWithDomain:@"接口返回数据格式出错" code:-1 userInfo:nil]);
                     }
                 }
                 else if (failure)
                 {
                     
                     failure([NSError errorWithDomain:@"接口出错" code:-1 userInfo:nil]);
                     
                 }else
                 {
                     
                     NSLog(@"[ERROR] failure not exist!");
                     
                 }
                 
                 
             }
             
         }
              failure:^(AFHTTPRequestOperation *operation, NSError *error)
         
         {
             failure(error);
             
         }];
        
        
    }
}
/*______上传 所问问题   包含文字 图片（声音）________**littleSun_zheng**/

/**
 *  请求Opinion Server Api 接口方法
 *
 *  @param request 自定义的Request请求
 *  @param userInfoId 对应人的唯一标示（用户本人  和  关系人）
 *  @param token token值
 *  @param imageAndVoiceDataArray  盛放图片 语音的数组
 *  @param success 请求成功,返回Response对象
 *  @param failure 请求失败
 *  @param cached  是否进行缓存
 */
+ (void)requestWithPOST:(NetWorkBaseRequest *)request WithImageDataArray:(NSMutableArray *)imageDataArray WithVoiceData:(NSData *)voiceData success:(void (^)(NetWorkBaseResponse *responseObject))success
                failure:(void (^)(NSError *error))failure
                  cache:(BOOL)cached
{
    
    if (!request) {
        NSLog(@"[ERROR] request cannot be NULL");
        if (failure) {
            
            failure([NSError errorWithDomain:@"" code:-1 userInfo:nil]);
        }
        return;
    }
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    [manager.requestSerializer setValue:@"multipart/form-data;charset=utf-8"forHTTPHeaderField:@"Content-Type"];
    
    manager.requestSerializer.timeoutInterval = 10;
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    [manager.requestSerializer setCachePolicy:NSURLRequestReturnCacheDataElseLoad];
    
    NSString *tokenValue = [SSKeychain passwordForService:[AppUtils appServiceName] account:[AppUtils tokenKey]];
    if (!tokenValue) {
        
        tokenValue = @"";
    }
    
    //        NSString *encryptParam = request.getEncrptPostDataString;
    
    [request.paramDic setValue:tokenValue forKey:@"token"];
    
    
    [manager POST:request.stringOfApiURLString parameters:request.paramDic constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
     {
         //对传进来的 图片  数组进行遍历
         for (int i = 0; i < imageDataArray.count; i++) {
             
             NSData *imgData = imageDataArray[i];
             
             //用这个当图片的名字，一起到图片名不重复的效果
             NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
             NSString *tupianming = [NSString stringWithFormat:@"yyyyMMddHHmmssSSSS%d",i];
             [dateFormatter setDateFormat:tupianming];
             NSString *pictname;
             NSString *picFileName;
             pictname = [NSString stringWithFormat:@"/%@.jpg",[dateFormatter stringFromDate:[NSDate date]]];
             picFileName = [NSString stringWithFormat:@"/%@file",[dateFormatter stringFromDate:[NSDate date]]];
             
             
             [formData appendPartWithFileData:imgData name:picFileName fileName:[NSString stringWithFormat:@"%@",pictname] mimeType:@"image/jpg"];
         }
         if(voiceData!=nil){
             
             //用这个当图片的名字，起到图片名不重复的效果
             NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
             NSString *tupianming = [NSString stringWithFormat:@"yyyyMMddHHmmssSSSS%@",@"luyin"];
             [dateFormatter setDateFormat:tupianming];
             NSString *luyinname;
             NSString *luyinFileName;
             luyinname = [NSString stringWithFormat:@"/%@.wav",[dateFormatter stringFromDate:[NSDate date]]];
             //让服务器识别这个音频的格式 为  wav
             luyinFileName = [NSString stringWithFormat:@"/%@.wav",[dateFormatter stringFromDate:[NSDate date]]];
             
             
             [formData appendPartWithFileData:voiceData name:luyinname fileName:luyinFileName mimeType:@"audio/x-wav"];
             
         }
         
     }
          success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         {
             
             NSDictionary *dic = responseObject;//operation.request.cachePolicy
             
             if (dic)
             {
                 @try{
                     
                     //                         NSError *error = nil;
                     //                         NSString *encryptKey = [dic objectForKey:@"encryptKey"];
                     //                         NSString *data = [dic objectForKey:@"data"];
                     //                         if (!encryptKey || !data) {
                     //                             failure([NSError errorWithDomain:@"接口返回数据格式出错" code:-1 userInfo:nil]);
                     //                             return ;
                     //                         }
                     //
                     //                         NSString* aesKey = [[Digest sharedInstance] rsaDecryptString:encryptKey];
                     //                         CocoaSecurityResult *text =  [CocoaSecurity aesDecryptWithBase64ESPC:data key:aesKey];
                     //
                     //                         if (!text.utf8String) {
                     //                             failure([NSError errorWithDomain:@"接口返回数据格式出错" code:-1 userInfo:nil]);
                     //                             return ;
                     //                         }
                     //                         NSDictionary *apiDic = [NSJSONSerialization JSONObjectWithData:text.data options:0 error:&error];
                     //
                     //                         if (!apiDic || error) {
                     //
                     //                             failure([NSError errorWithDomain:@"接口返回数据格式出错" code:-1 userInfo:nil]);
                     //                             return ;
                     //                         }
                     
                     //解决若是json格式出错崩溃问题，判断status=0为成功
                     NSString *responseClassName =  [NetWorkUtil replaceCharacter:@"Request" withString:@"Response" inString:NSStringFromClass([request class])];
                     NetWorkBaseResponse *response = [[NSClassFromString(responseClassName) alloc] initWithDictionary:dic];
                     if (response && success) {
                         //缓存
                         if (cached) {
                             NSCachedURLResponse *resp = [[NSCachedURLResponse alloc] initWithResponse:operation.response data:operation.responseData];
                             [[NSURLCache sharedURLCache] storeCachedResponse:resp forRequest:operation.request];
                         }
                         success(response);
                     }else{
                         failure([NSError errorWithDomain:@"接口出错" code:-1 userInfo:nil]);
                     }
                 }@catch(NSException *exception) {
                     failure([NSError errorWithDomain:@"接口返回数据格式出错" code:-1 userInfo:nil]);
                 }
             }
             else if (failure)
             {
                 
                 failure([NSError errorWithDomain:@"接口出错" code:-1 userInfo:nil]);
                 
             }else
             {
                 
                 NSLog(@"[ERROR] failure not exist!");
                 
             }
         }
     }
          failure:^(AFHTTPRequestOperation *operation, NSError *error)
     
     {
         failure(error);
         
     }];
}

/**
 *  请求Opinion Server Api 接口方法
 *
 *  @param request 自定义的Request请求
 *  @param success 请求成功,返回Response对象
 *  @param failure 请求失败
 *  @param cached  是否进行缓存
 */
+ (void)requestWithGET:(NetWorkBaseRequest *)request
               success:(void (^)(NetWorkBaseResponse *responseObject))success
               failure:(void (^)(NSError *error))failure
                 cache:(BOOL)cached
{
    
    if (!request) {
        NSLog(@"[ERROR] request cannot be NULL");
        if (failure) {
            failure([NSError errorWithDomain:@"" code:-1 userInfo:nil]);
        }
        return;
    }
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    
    NSString *tokenValue = [SSKeychain passwordForService:[AppUtils appServiceName] account:[AppUtils tokenKey]];
    if (!tokenValue) {
        tokenValue = @"";
    }
    [manager GET:request.stringOfApiURLString parameters:@{@"encryptParam": request.getEncrptPostDataString,@"token":tokenValue} success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = responseObject;
        if (dic) {
            @try{
                
                NSError *error = nil;
                NSString *encryptKey = [dic objectForKey:@"encryptKey"];
                NSString *data = [dic objectForKey:@"data"];
                if (!encryptKey || !data) {
                    failure([NSError errorWithDomain:@"接口返回数据格式出错" code:-1 userInfo:nil]);
                    return ;
                }
                
                NSString* aesKey = [[Digest sharedInstance] rsaDecryptString:encryptKey];
                CocoaSecurityResult *text =  [CocoaSecurity aesDecryptWithBase64ESPC:data key:aesKey];
                
                if (!text.utf8String) {
                    failure([NSError errorWithDomain:@"接口返回数据格式出错" code:-1 userInfo:nil]);
                    return ;
                }
                
                NSDictionary *apiDic = [NSJSONSerialization JSONObjectWithData:text.data options:0 error:&error];
                if (!apiDic || error) {
                    failure([NSError errorWithDomain:@"接口返回数据格式出错" code:-1 userInfo:nil]);
                    return ;
                }
                
                //解决若是json格式出错崩溃问题，判断status=0为成功
                NSString *responseClassName =  [NetWorkUtil replaceCharacter:@"Request" withString:@"Response" inString:NSStringFromClass([request class])];
                NetWorkBaseResponse *response = [[NSClassFromString(responseClassName) alloc] initWithDictionary:apiDic];
                if (response && success) {
                    //缓存
                    if (cached) {
                        NSCachedURLResponse *resp = [[NSCachedURLResponse alloc] initWithResponse:operation.response data:operation.responseData];
                        [[NSURLCache sharedURLCache] storeCachedResponse:resp forRequest:operation.request];
                    }
                    success(response);
                }else{
                    failure([NSError errorWithDomain:@"接口出错" code:-1 userInfo:nil]);
                }
            }@catch(NSException *exception) {
                failure([NSError errorWithDomain:@"接口返回数据格式出错" code:-1 userInfo:nil]);
            }
        }else if (failure) {
            failure([NSError errorWithDomain:@"接口出错" code:-1 userInfo:nil]);
        }else{
            NSLog(@"[ERROR] failure not exist!");
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (failure) {
            failure(error);
        }else{
            NSLog(@"[ERROR] failure not exist!");
        }
    }];
}

@end


